I am posting my own binary search algorithm. BTW you can use QFontMetrics instead of QPainter if you want.
int FontUtils::FittingLength(const QString& s, QPainter &p, const QRectF& rect,
int flags/* = Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap*/)
{
QRectF r = p.boundingRect(rect, flags, s);
if (r.height() <= rect.height()) // String fits rect.
return s.length();
// Apply binary search.
QString sub;
int left = 0, right = s.length()-1;
do
{
int pivot = (left + right)>>1; // Middle point.
sub = s.mid(0, pivot+1);
r = p.boundingRect(rect, flags, sub);
if (r.height() > rect.height()) // Doesn't fit.
right = pivot-1;
else
left = pivot+1;
} while (left < right);
left++; // Length of string is one char more.
// Remove trailing word if it doesn't fit.
if ( !s.at(left).isSpace() && !s.at(left+1).isSpace() )
{
while ( (--left > 0) && !sub.at(left).isSpace() );
left++;
}
return left;
}